import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

/// Excel解析结果展示组件
/// 显示解析状态、数据预览、解析错误等信息
class ExcelParseResultWidget extends ConsumerStatefulWidget {
  final String excelPlanId;
  final Function(Map<String, dynamic>)? onGenerateTasks;

  const ExcelParseResultWidget({
    super.key,
    required this.excelPlanId,
    this.onGenerateTasks,
  });

  @override
  ConsumerState<ExcelParseResultWidget> createState() =>
      _ExcelParseResultWidgetState();
}

class _ExcelParseResultWidgetState extends ConsumerState<ExcelParseResultWidget>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  bool _isLoading = false;
  bool _isGeneratingTasks = false;
  ExcelParseResult? _parseResult;
  String? _error;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
    _loadParseResult();
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  /// 加载解析结果
  Future<void> _loadParseResult() async {
    setState(() {
      _isLoading = true;
      _error = null;
    });

    try {
      // TODO: 调用实际的API获取解析结果
      // final excelProvider = ref.read(excelProviderProvider.notifier);
      // final result = await excelProvider.getParseResult(widget.excelPlanId);

      // 模拟数据
      await Future.delayed(const Duration(seconds: 1));
      setState(() {
        _parseResult = ExcelParseResult.mockData();
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _error = '加载解析结果失败: ${e.toString()}';
        _isLoading = false;
      });
    }
  }

  /// 生成待办任务
  Future<void> _generateTasks() async {
    if (_parseResult == null) return;

    setState(() {
      _isGeneratingTasks = true;
    });

    try {
      // TODO: 调用AI生成任务API
      await Future.delayed(const Duration(seconds: 2));

      if (widget.onGenerateTasks != null) {
        widget.onGenerateTasks!(_parseResult!.toJson());
      }

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('任务生成成功'),
            backgroundColor: Colors.green,
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('任务生成失败: ${e.toString()}'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } finally {
      setState(() {
        _isGeneratingTasks = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: const EdgeInsets.all(16),
      child: Column(
        children: [
          // 标题栏
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.blue.shade50,
              borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(12),
                topRight: Radius.circular(12),
              ),
            ),
            child: Row(
              children: [
                const Icon(Icons.analytics, color: Colors.blue),
                const SizedBox(width: 8),
                Text(
                  'Excel解析结果',
                  style: Theme.of(context).textTheme.titleLarge,
                ),
                const Spacer(),
                if (_parseResult != null && !_isGeneratingTasks)
                  ElevatedButton.icon(
                    onPressed: _generateTasks,
                    icon: const Icon(Icons.auto_awesome),
                    label: const Text('生成任务'),
                  ),
                if (_isGeneratingTasks)
                  const Row(
                    children: [
                      SizedBox(
                        width: 16,
                        height: 16,
                        child: CircularProgressIndicator(strokeWidth: 2),
                      ),
                      SizedBox(width: 8),
                      Text('生成中...'),
                    ],
                  ),
              ],
            ),
          ),

          // 内容区域
          if (_isLoading)
            const Padding(
              padding: EdgeInsets.all(32),
              child: Column(
                children: [
                  CircularProgressIndicator(),
                  SizedBox(height: 16),
                  Text('正在解析Excel文件...'),
                ],
              ),
            )
          else if (_error != null)
            Padding(
              padding: const EdgeInsets.all(16),
              child: Container(
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: Colors.red.shade50,
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: Colors.red.shade200),
                ),
                child: Column(
                  children: [
                    const Icon(Icons.error, color: Colors.red, size: 48),
                    const SizedBox(height: 16),
                    Text(
                      _error!,
                      style: const TextStyle(color: Colors.red),
                      textAlign: TextAlign.center,
                    ),
                    const SizedBox(height: 16),
                    ElevatedButton(
                      onPressed: _loadParseResult,
                      child: const Text('重试'),
                    ),
                  ],
                ),
              ),
            )
          else if (_parseResult != null)
            _buildParseResultContent(),
        ],
      ),
    );
  }

  /// 构建解析结果内容
  Widget _buildParseResultContent() {
    return Column(
      children: [
        // 解析概要
        _buildParseSummary(),

        // Tab导航
        TabBar(
          controller: _tabController,
          tabs: const [
            Tab(text: '数据预览'),
            Tab(text: '需求信息'),
            Tab(text: '统计分析'),
          ],
        ),

        // Tab内容
        SizedBox(
          height: 400,
          child: TabBarView(
            controller: _tabController,
            children: [
              _buildDataPreview(),
              _buildRequirementInfo(),
              _buildStatistics(),
            ],
          ),
        ),
      ],
    );
  }

  /// 构建解析概要
  Widget _buildParseSummary() {
    return Container(
      padding: const EdgeInsets.all(16),
      child: Row(
        children: [
          _buildSummaryCard(
            '总行数',
            _parseResult!.totalRows.toString(),
            Icons.table_rows,
            Colors.blue,
          ),
          const SizedBox(width: 16),
          _buildSummaryCard(
            '有效数据',
            _parseResult!.validRows.toString(),
            Icons.check_circle,
            Colors.green,
          ),
          const SizedBox(width: 16),
          _buildSummaryCard(
            '需求数量',
            _parseResult!.requirements.length.toString(),
            Icons.assignment,
            Colors.orange,
          ),
        ],
      ),
    );
  }

  /// 构建概要卡片
  Widget _buildSummaryCard(
      String title, String value, IconData icon, Color color) {
    return Expanded(
      child: Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: color.withValues(alpha: 0.1),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Column(
          children: [
            Icon(icon, color: color, size: 24),
            const SizedBox(height: 8),
            SelectableText(
              value,
              style: TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
                color: color,
              ),
            ),
            SelectableText(
              title,
              style: TextStyle(
                fontSize: 12,
                color: Colors.grey.shade600,
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建数据预览
  Widget _buildDataPreview() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SelectableText(
            '前${_parseResult!.previewData.length}行数据预览',
            style: const TextStyle(fontWeight: FontWeight.w500),
          ),
          const SizedBox(height: 12),
          SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: DataTable(
              columns: _parseResult!.headers
                  .map((header) => DataColumn(
                        label: SelectableText(
                          header,
                          style: const TextStyle(fontWeight: FontWeight.bold),
                        ),
                      ))
                  .toList(),
              rows: _parseResult!.previewData
                  .map((row) => DataRow(
                        cells: row
                            .map((cell) => DataCell(
                                  SelectableText(cell?.toString() ?? ''),
                                ))
                            .toList(),
                      ))
                  .toList(),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建需求信息
  Widget _buildRequirementInfo() {
    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: _parseResult!.requirements.length,
      itemBuilder: (context, index) {
        final requirement = _parseResult!.requirements[index];
        return Card(
          margin: const EdgeInsets.only(bottom: 12),
          child: Padding(
            padding: const EdgeInsets.all(12),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 8,
                        vertical: 4,
                      ),
                      decoration: BoxDecoration(
                        color: Colors.blue.shade100,
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: SelectableText(
                        '需求 ${index + 1}',
                        style: const TextStyle(
                          fontSize: 12,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    const Spacer(),
                    _getPriorityChip(requirement['priority']),
                  ],
                ),
                const SizedBox(height: 8),
                SelectableText(
                  requirement['title'] ?? '未命名需求',
                  style: const TextStyle(
                    fontWeight: FontWeight.w500,
                    fontSize: 16,
                  ),
                ),
                if (requirement['description'] != null) ...[
                  const SizedBox(height: 4),
                  SelectableText(
                    requirement['description'],
                    style: TextStyle(
                      color: Colors.grey.shade600,
                      fontSize: 14,
                    ),
                  ),
                ],
              ],
            ),
          ),
        );
      },
    );
  }

  /// 构建统计分析
  Widget _buildStatistics() {
    return Padding(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const SelectableText(
            '数据质量分析',
            style: TextStyle(fontWeight: FontWeight.w500, fontSize: 16),
          ),
          const SizedBox(height: 16),

          // 数据质量指标
          _buildStatItem('数据完整性',
              '${((_parseResult!.validRows / _parseResult!.totalRows) * 100).toStringAsFixed(1)}%'),
          _buildStatItem(
              '空值行数', '${_parseResult!.totalRows - _parseResult!.validRows}'),
          _buildStatItem('重复数据', '0'),

          const SizedBox(height: 24),
          const SelectableText(
            '需求分析',
            style: TextStyle(fontWeight: FontWeight.w500, fontSize: 16),
          ),
          const SizedBox(height: 16),

          // 需求统计
          _buildStatItem('总需求数', '${_parseResult!.requirements.length}'),
          _buildStatItem('高优先级',
              '${_parseResult!.requirements.where((r) => r['priority'] == 'HIGH').length}'),
          _buildStatItem('中优先级',
              '${_parseResult!.requirements.where((r) => r['priority'] == 'MEDIUM').length}'),
          _buildStatItem('低优先级',
              '${_parseResult!.requirements.where((r) => r['priority'] == 'LOW').length}'),
        ],
      ),
    );
  }

  /// 构建统计项
  Widget _buildStatItem(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          SelectableText(label),
          Text(
            value,
            style: const TextStyle(fontWeight: FontWeight.w500),
          ),
        ],
      ),
    );
  }

  /// 获取优先级标签
  Widget _getPriorityChip(String? priority) {
    Color color;
    String text;

    switch (priority) {
      case 'HIGH':
        color = Colors.red;
        text = '高';
        break;
      case 'MEDIUM':
        color = Colors.orange;
        text = '中';
        break;
      case 'LOW':
        color = Colors.green;
        text = '低';
        break;
      default:
        color = Colors.grey;
        text = '未知';
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: color.withValues(alpha: 0.3)),
      ),
      child: SelectableText(
        text,
        style: TextStyle(
          color: color,
          fontSize: 12,
          fontWeight: FontWeight.w500,
        ),
      ),
    );
  }
}

/// Excel解析结果数据模型
class ExcelParseResult {
  final int totalRows;
  final int validRows;
  final List<String> headers;
  final List<List<dynamic>> previewData;
  final List<Map<String, dynamic>> requirements;
  final Map<String, dynamic> statistics;

  const ExcelParseResult({
    required this.totalRows,
    required this.validRows,
    required this.headers,
    required this.previewData,
    required this.requirements,
    required this.statistics,
  });

  factory ExcelParseResult.fromJson(Map<String, dynamic> json) {
    return ExcelParseResult(
      totalRows: json['totalRows'] as int,
      validRows: json['validRows'] as int,
      headers: List<String>.from(json['headers'] as List),
      previewData: (json['previewData'] as List)
          .map((row) => List<dynamic>.from(row as List))
          .toList(),
      requirements: List<Map<String, dynamic>>.from(
        (json['requirements'] as List)
            .map((req) => Map<String, dynamic>.from(req as Map)),
      ),
      statistics: Map<String, dynamic>.from(json['statistics'] as Map),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'totalRows': totalRows,
      'validRows': validRows,
      'headers': headers,
      'previewData': previewData,
      'requirements': requirements,
      'statistics': statistics,
    };
  }

  /// 创建模拟数据
  factory ExcelParseResult.mockData() {
    return ExcelParseResult(
      totalRows: 25,
      validRows: 23,
      headers: ['序号', '功能模块', '需求描述', '优先级', '负责人', '预期完成时间'],
      previewData: [
        [1, '用户管理', '用户注册登录功能', '高', '张三', '2024-02-01'],
        [2, '项目管理', '项目创建和编辑', '中', '李四', '2024-02-05'],
        [3, 'Excel处理', 'Excel文件上传解析', '高', '王五', '2024-02-03'],
        [4, '任务管理', '待办任务CRUD', '中', '赵六', '2024-02-07'],
        [5, 'AI助手', '智能需求分析', '高', '孙七', '2024-02-10'],
      ],
      requirements: [
        {
          'id': 1,
          'title': '用户管理系统',
          'description': '实现用户注册、登录、权限管理等功能',
          'priority': 'HIGH',
          'assignee': '张三',
          'deadline': '2024-02-01',
        },
        {
          'id': 2,
          'title': '项目管理功能',
          'description': '项目的创建、编辑、删除和查看功能',
          'priority': 'MEDIUM',
          'assignee': '李四',
          'deadline': '2024-02-05',
        },
        {
          'id': 3,
          'title': 'Excel处理引擎',
          'description': 'Excel文件的上传、解析和数据提取',
          'priority': 'HIGH',
          'assignee': '王五',
          'deadline': '2024-02-03',
        },
      ],
      statistics: {
        'dataQuality': 92.0,
        'emptyRows': 2,
        'duplicateRows': 0,
        'priorityDistribution': {
          'HIGH': 2,
          'MEDIUM': 1,
          'LOW': 0,
        },
      },
    );
  }
}
